/**
 * Created by Administrator on 2017/1/10.
 */

var pomelo = require('pomelo');
var GlobalConfig = require('../../../config/config.json');
var messageService = require('../messageService');
var roomManager = require('../../logic/world/roomManager');
var systemConfig = require('../../../config/systemConfig.json')
// 玩家数据
function Player(uid) {
    this.openid = '';
    this.uid = uid;            // 玩家编号
    this.user = {};             // 玩家数据
    this.dirty = {};            // 数据是否被修改
    this.isNew = false;        // 是否是新用户
}

Player.create = function (uid) {
    var initUser = {
        "_id": uid,                  // 角色编号
        "ai": 1,
        "info": {
            "name": "",             // 角色名
            "headpic": "",         // 头像
            "sex": 1,               // 性别
            "province": "",        // 省份
            "signature": "",       // 个性签名
            "createTime": 0,       // 创建时间
            "createIP": "",        // 创建时的IP
        },

        "status": {
            "card": 0,              // 房卡
            "cash": 0,              // 元宝(废弃)
            "coin": 0,              // 金币
            "score": 0,             // 积分
        },

        "marks": {
            "loginTime": 0,        // 最近登录时间
            "loginIP": "",         // 最近登录IP
            "logoutTime": 0,       // 最近离线时间
        },

        "reports": [],             // 战报ID列表

        "invite": {
            "inviter": 0,           // 邀请者
            "inviteTime": 0,        // 邀请时间
        },

        "gm": {
            "level": 0,            // GM等级 0普通用户 99超级管理员
        },

        "stat": {
            "payCard": 0,          // 累计充值房卡
        },

        "dayVars": {         // 每日变量
            day: 0,                // 距离1970/1/1的天数
            SevenDayReward: 0,         //七日登陆奖励
            SignReward: 0,              //签到奖励
            /*
             dailyReward: 0,        // 每日登录奖励
             shareReward: 0,        // 每日分享奖励
             bigWheelTimes: 0,      // 幸运大转盘抽奖次数
             */
        },

        "weekVars": {       // 每周变量
            /*
             playRound: 0,           // 房卡场局数
             */
        },

        "activity": {        // 活动数据
        },

        "dailyActivity": {       // 每日活动数据
        },

        "tasks": {              // 任务数据

        },

        "telephone": {
            code: 0,            // 验证码
            number: 0,          // 手机号码
        },

        "mails": {
            maxMailID: 0,       // 最大邮件编号
            mailList: {              // 邮件
                // {
                //     id:             // 邮件编号
                //     time:           // 发送时间
                //     content:        // 内容
                //     status:         // 状态(0:未读|1:已读)
                // }
            }
        }

        /**
         动态字段
         robot: 1， 是机器人会设置此字段
         privilege: 0,  特殊权限
         block: 0,  封号标志
         controlValue: 0, 控制值
         Club:0,俱乐部,
         cardRoomStat: {    //房卡场统计数据，废弃
            $gameType: {
                winScore: 0,    // 总赢分
                loseScore: 0,   // 总输分
                play: 0,        // 总次数
                playRound: 0,   // 总局数
            }
         }

         playStat: {    // 游戏统计
                winScore: 0,    // 总赢分
                loseScore: 0,   // 总输分
                play: 0,        // 总次数
                playRound: 0,   // 总局数
         |,

         activitySign: {
            monthCount: 0,  //  本月累计签到
            seriesDays: 0,  // 连续签到
            lastTime: 0,    //上次签到时间
            signs: [], //  本月签到
         }
         "authenticationInfo": {   //实名认证
            name: 0,    //姓名
            phone: 0,   //电话
            id: 0       //身份证
        }
         "storageBox": {
            coin: 0,
            card: 0,
         },       //储存金币


         "groups": [],      // 所加入的群主id

         */
    };

    //-------------------------------------------------------------------------
    // 添加初始化邮件
    var mails = initUser.mails;
    mails.maxMailID = 1;
    mails.mailList[1] = {
        id: 1,                          // 邮件编号
        time: Date.getStamp(),          // 创建时间
        content: "天天麻将，祝您玩的愉快！",               // 邮件内容
        status: 0                       // 邮件状态
    };
    //-------------------------------------------------------------------------

    initUser.info.createTime = Date.getStamp();
    return initUser;
};

Player.prototype = {

    // 初始化角色
    init: function (fields, callback) {
        if (fields && (typeof (fields) == "object")
            && Object.getOwnPropertyNames(fields) > 0) {
            // 加载部分数据
            fields["ai"] = 1;
        }

        var player = this;

        // 加载玩家数据
        DB.user.findOne({ _id: player.uid }, fields, function (err, doc) {
            if (doc) {
                player.user = doc;
                player._init();

                callback && callback(true);
            } else {
                if (err) {
                    callback && callback(false);
                } else {
                    // 创建新用户
                    player.user = Player.create(player.uid);
                    player.isNew = true;
                    player.alterResourceNotSync(gGlobalManager.getConfig("initResource"), "initResource");
                    player.clearDirty();

                    DB.user.insertOne(player.user, function (err, res) {
                        if (err) {
                            callback && callback(false);
                        } else {
                            callback && callback(true);
                        }
                    });
                }
            }
        });
    },

    _init: function () {
        var user = this.user;
        if (!user.hasOwnProperty('stat')) {
            user.stat = {};
        }

        if (!user.hasOwnProperty('activity')) {
            user.activity = {};
        }

        if (!user.hasOwnProperty('dailyActivity')) {
            user.dailyActivity = {};
        }
    },

    // 保存用户数据
    save: function (force, callback) {
        var keys = Object.keys(this.dirty);
        if (keys.length < 1) {
            callback && callback();
            return;
        }

        if (keys.length < 3 && !force) {
            callback && callback();
            return;
        }

        var updates = {};

        var user = this.user;
        var sets = {};
        for (var i = 0; i < keys.length; ++i) {
            var key = keys[i];
            sets[key] = user[key];
        }

        this.clearDirty();
        DB.user.update({ _id: this.uid }, { '$set': sets }, function (err, result) {
            if (err) {
                callback && callback(err);
            } else {
                callback && callback();
            }
        }.bind(this));
    },

    // 标记数据被修改
    markDirty: function (key) {
        this.dirty[key] = 1;
    },

    clearDirty: function () {
        this.dirty = {};
    },

    ///////////////////////////////////////////////////
    getInviterUid: function () {
        if (systemConfig["UseType"]["Inviter"]) {
            return this.user.invite.inviter;
        } else {
            return this.user.Club;
        }
    },
    setInviterUid: function (inviterUid,time) {
        if (systemConfig["UseType"]["Inviter"]) {
            this.user.invite.inviter = inviterUid;
            this.user.invite.time = time;
        } else {
            this.user.Club = inviterUid;
        }
    },
    isRobot: function () {
        return this.user.robot ? true : false;
    },

    getResource: function (key) {
        if (key) {
            return this.user.status[key] || 0;
        } else {
            return this.user.status;
        }
    },

    /**
     * 检查资源是否足够
     * @param name 资源名称，也可以用对象表示多项资源，key为名称,value为值
     * @param value 资源值
     * @returns {boolean}
     */
    checkResource: function (name, value) {
        if (ExObject.isObject(name)) {
            var resource = name;
            for (var key in resource) {
                var num = resource[key];
                if (!isNaN(num) && (this.getResource(key) < num)) {
                    return false;
                }
            }
            return true;
        } else {
            return this.getResource(name) >= value;
        }
    },

    /**
     * 检查资源是否足够并返回错误码
     * @param name 资源名称，也可以用对象表示多项资源，key为名称,value为值
     * @param value 资源值
     * returns {number}
     */
    checkResourceCode: function (name, value) {
        if (ExObject.isObject(name)) {
            var resource = name;
            for (var key in resource) {
                var num = resource[key];
                if (Def.isValidResourceName(key) && !isNaN(num) && (this.getResource(key) < num)) {
                    return Code['LACK_OF_' + key.toUpperCase()];
                }
            }
        } else {
            if (Def.isValidResourceName(name) && (this.getResource(name) < value)) {
                return Code['LACK_OF_' + name.toUpperCase()];
            }
        }

        return Code.SUCCESS;
    },

    /**
     * 消耗资源
     * @param name 资源名称，如果为对象则想当于(resourceObj, notSync)
     * @param value 资源数量
     * @param reason 触发原因
     */
    costResource: function (name, value, reason, arg1) {
        if (ExObject.isObject(name)) {
            this._alterResource(ExObject.minus(clone(name)), true, value, reason);
        } else {
            this._alterResource(ExObject.build(name, -value), true, reason, arg1);
        }
    },

    /**
     * 添加资源
     * @param name 资源名称，如果为对象则想当于(resourceObj, reason)
     * @param value 资源数量
     * @param reason 触发原因
     */
    addResource: function (name, value, reason, arg1) {
        if (ExObject.isObject(name)) {
            this._alterResource(name, true, value, reason);
        } else {
            this._alterResource(ExObject.build(name, value), true, reason, arg1);
        }
    },

    /**
     * 修改资源
     * @param name 资源名称，如果为对象则想当于(resourceObj, reason)
     * @param value 资源数量
     * @param reason 触发原因
     */
    alterResource: function (name, value, reason, arg1) {
        if (ExObject.isObject(name)) {
            this._alterResource(name, true, value, reason);
        } else {
            this._alterResource(ExObject.build(name, value), true, reason, arg1);
        }
    },

    alterResourceNotSync: function (resource, reason, arg1) {
        this._alterResource(resource, false, reason, arg1);
    },

    _alterResource: function (resource, sync, reason, arg1) {
        var syncUser = {};
        var typeCount = 0;
        for (var key in resource) {
            var num = resource[key];
            if (!isNaN(num)) {
                ExObject.addNumber0(this.user.status, key, +num);
                syncUser[key] = this.user.status[key];
                typeCount++;
            }
        }

        if (typeCount == 0) {
            return;
        }

        this.markDirty("status");
        this.sendUserStatusChanged(reason);

        if (sync) {
            this.syncGameUser(syncUser, function () {
            });
        }

        var log = clone(resource);
        log.uid = this.uid;
        log.t = Date.stdFormatedString();
        log.r = reason;
        log.a1 = arg1;
        log.s = syncUser;
        DB.log.save(log);
    },

    /**
     * 充值房卡
     * @param num
     */
    payCard: function (num) {
        this.addResource("card", num, "pay");
        ExObject.addNumber(this.user.stat, "payCard", num);
    },
    feedbackAgency: function (info) {
        //写入记录
        var money = info["money"] || 0;
        //var money = 100;
        var time = info["time"] || Date.parse(new Date()) / 1000;
        var order = info["order"];

        var myUid = this.uid;
        var myName = this.user.name || '';
        var inviter = this.getInviterUid();

        // var myUid = 222423;
        // var myName = "this.user.name";
        // var inviter = 110002;
        if (!inviter) {
            logger.debug("player havent inviter");
            return;
        }
        logger.debug("feedbackAgency money=%j time=%d order=%s myUid=%d myName=%s inviter=%d",
            money, time, order, myUid, myName, inviter);

        async.waterfall([function (cb) {
            var todoList = [];
            var agentFeedback = [];
            async.series([
                function (sericb) {
                    var sql = util.format("SELECT level,online_rebate1,online_rebate2,online_rebate3 FROM %sagent",
                        GlobalConfig.mysql.prefix);
                    SQL.query(sql, function (err, results) {
                        if (err) {
                            sericb(err); return;
                        }
                        results = JSON.parse(JSON.stringify(results));
                        agentFeedback = results;
                        sericb(null);
                    });
                },
                function (sericb) {
                    async.waterfall([
                        function (incb) {
                            var sql = util.format("SELECT refer,total_rebate FROM %suser WHERE user_id=%d",
                                GlobalConfig.mysql.prefix, inviter);
                            SQL.query(sql, function (err, results) {
                                if (err) {
                                    incb(err); return;
                                }
                                var ref = JSON.parse(JSON.stringify(results));
                                if (!ref.length) {
                                    incb("mysql not find result")
                                    return;
                                }
                                todoList.push({ "ref": inviter, "rebateNow": ref[0]['total_rebate'] });
                                //todoList.push({"ref":ref[0]['refer'],"rebateNow":ref[0]['total_rebate']});
                                incb(null, ref[0]["refer"]);
                            });
                        },
                        function (re1, incb) {
                            if (re1 == 0) {
                                todoList.push(0);
                                incb(null, re1)
                                return;
                            }
                            var sql = util.format("SELECT refer,total_rebate FROM %suser WHERE user_id=%d",
                                GlobalConfig.mysql.prefix, re1);
                            SQL.query(sql, function (err, results) {
                                if (err) {
                                    incb(err);
                                    return;
                                }
                                var ref = JSON.parse(JSON.stringify(results));
                                todoList.push({ "ref": re1, "rebateNow": ref[0]['total_rebate'] });
                                incb(null, ref[0]['refer']);
                            });
                        },
                        function (re2, incb) {
                            if (re2 == 0) {
                                todoList.push(0);
                                incb(null, re2)
                                return;
                            }
                            var sql = util.format("SELECT refer,total_rebate FROM %suser WHERE user_id=%d",
                                GlobalConfig.mysql.prefix, re2);
                            SQL.query(sql, function (err, results) {
                                if (err) {
                                    incb(err);
                                    return;
                                }
                                var ref = JSON.parse(JSON.stringify(results));
                                todoList.push({ "ref": re2, "rebateNow": ref[0]['total_rebate'] });
                                incb(null, ref[0]['refer']);
                            });
                        },
                    ], function (err, results) {
                        if (err) {
                            sericb(err);
                            return;
                            //logger.error("uid=%d hallHandler.feedback sql=%s err=%j", uid, sql, err.message);
                        }
                        sericb(null, todoList)
                    });
                }
            ], function (err) {
                if (err) {
                    cb(err);
                    return;
                }
                cb(null, todoList, agentFeedback)
            });

        }, function (todo, agentlist, cb) {

            logger.debug("player inviterList %j", todo)
            logger.debug("player agentList %j", agentlist)
            var mapLevel = {};
            agentlist.forEach(function (v) {
                mapLevel[v["level"]] = v;
            });
            var filtered = todo.filter(function (v) {
                return v != 0;
            });
            // if (filtered.length > 2) {
            //     cb("inviter too many")
            //     return;
            // }
            var rebates = mapLevel[filtered.length];

            var rebateList = [{ "scale": rebates['online_rebate1'], "uid": todo[0] }, { "scale": rebates['online_rebate2'], "uid": todo[1] },
            { "scale": rebates['online_rebate3'], "uid": todo[2] }]


            logger.debug("todo rebateList %j", rebateList);


            async.each(rebateList, function (scale, eachback) {
                console.log(scale);
                if (!scale["uid"] || !scale["scale"]) {
                    logger.debug("dont need save")
                    eachback();
                    return;
                }
                async.series([
                    function (eachserback) {

                        var sql = util.format("UPDATE %suser SET total_rebate = %d WHERE user_id=%d",
                            GlobalConfig.mysql.prefix,
                            (scale['uid']['rebateNow'] + (money * (scale["scale"] / 100))),
                            scale["uid"]["ref"]
                        );
                        SQL.query(sql, function (err, results) {
                            if (err) {
                                logger.error("player.feedback update err=%j", err.message);
                                eachserback(err);
                                return;
                            }
                            eachserback();

                        });
                    },
                    function (eachserback) {

                        var sql = util.format("INSERT INTO %sonlinerebate(user_id, buy_user_id, buy_id, rebate, rebate_scale, add_time, name,refer,amount) value(%d, %d, %s, %d, %d, %d, %s,%d,%d)",
                            GlobalConfig.mysql.prefix,
                            scale["uid"]["ref"],
                            myUid,
                            SQL.escape(order),
                            money * (scale["scale"] / 100),
                            scale["scale"],
                            time / 1000,
                            SQL.escape(myName),
                            inviter,
                            money);
                        SQL.query(sql, function (err, results) {
                            if (err) {

                                logger.error("player.feedback insert err=%j", err.message);
                                //logger.error("uid=%d hallHandler.feedback sql=%s err=%j", uid, sql, err.message);
                                eachserback(err);
                                return;
                            }
                            eachserback();

                        });
                    },
                ], function (err) {
                    if (err) {
                        console.log("err12")
                        eachback(err)
                        return;
                    }
                    eachback()
                });

            }, function (err) {
                if (err) {
                    cb(err)
                    return;
                }
                cb(null, "sucess");
            })
        }], function (err, result) {
            if (err) {
                logger.debug("feedbackAgencyErr %j", err)
                return;
            }
        });



        // var sql = util.format("QUERY INTO %sfeedback(uid, uname, type, content, attach, add_time, `status`) value(%d, %s, %s, %s, %s, %d, %d)",
        //     GlobalConfig.mysql.prefix, uid, SQL.escape(player.user.info.name), Def.Feedback[msg.type] || 0, SQL.escape(msg.content), SQL.escape(msg.attach), Date.getStamp(), 0);
        // SQL.query(sql, function (err, results) {
        //     if (err) {
        //         logger.error("uid=%d hallHandler.feedback sql=%s err=%j", uid, sql, err.message);
        //     }
        // });


    },
    /**
     * 是否在线
     * @returns {boolean}
     */
    isOnline: function () {
        return gSessionManager.isUserOnline(this.uid);
    },

    /**
     * 发送消息
     * @param route
     * @param msg
     */
    send: function (route, msg) {
        gSessionManager.sendToUser(this.uid, route, msg);
    },

    ///////////////////////////////////////////////////
    getDayVar: function (attr) {
        this.checkDayVars();
        return this.user.dayVars[attr] || 0;
    },

    setDayVar: function (attr, value) {
        this.user.dayVars[attr] = value;
        this.markDirty('dayVars');
    },

    addDayVar: function (attr, value) {
        this.checkDayVars();
        ExObject.addNumber0(this.user.dayVars, attr, value);
        this.markDirty('dayVars');
    },

    getWeekVar: function (attr) {
        this.checkDayVars();

        if (!this.user.weekVars) {
            this.user.weekVars = {};
        }

        return this.user.weekVars[attr] || 0;
    },

    setWeekVar: function (attr, value) {

        if (!this.user.weekVars) {
            this.user.weekVars = {};
        }

        this.user.weekVars[attr] = value;
        this.markDirty('weekVars');
    },

    addWeekVar: function (attr, value) {
        this.checkDayVars();

        if (!this.user.weekVars) {
            this.user.weekVars = {};
        }

        ExObject.addNumber0(this.user.weekVars, attr, value);
        this.markDirty('weekVars');
    },

    checkDayVars: function () {
        var nowDay = (new Date()).getDays();
        var vars = this.user.dayVars;
        if (!vars || vars.day != nowDay) {
            var oldDay = vars.day || 0;

            this.user.dayVars = { 'day': nowDay };
            this.markDirty('dayVars');
            this.onNewDay();

            if (Date.calcWeeksFromDays(oldDay) != Date.calcWeeksFromDays(nowDay)) {
                this.user.weekVars = {};
                this.markDirty("weekVars");
                this.onNewWeek();
            }
        }
    },

    ///////////////////////////////////////////////////
    onNewDay: function () {
        if (this.user.gameStat) {
            this.user.gameStat = {};
            this.markDirty('gameStat');
        }

        this.user.dailyActivity = {};
        this.markDirty("dailyActivity");

        this.save(true);
    },

    onNewWeek: function () {

    },

    ///////////////////////////////////////////////////

    // 保存战报
    addReport: function (reportId) {
        var reports = this.user.reports || [];

        reports.unshift(reportId);
        // TODO 战报数量
        if (reports.length > GlobalConfig.logic.reportNum) {
            reports = reports.splice(0, reports.length - GlobalConfig.logic.reportNum);
        }
        this.user.reports = reports;
        this.markDirty("reports");
    },

    getReports: function () {
        return this.user.reports || [];
    },

    getGmLevel: function () {
        if (this.user.gm) {
            return this.user.gm.level || 0;
        }
        return 0;
    },
    isAgency: function () {
        return (this.getGmLevel() >= 1 && this.getGmLevel() <= 10) ? true : false;
    },
    setGmLevel: function (level) {
        var user = this.user;
        if (!user.gm) {
            user.gm = { 'level': 0 };
        }

        user.gm.level = level;
        this.markDirty("gm");
        this.save(true);
    },

    setSelfGroup: function () {
        var uid = this.user._id;
        gGroupManager.agreeJoin(uid, uid, function (err, p) {
            if (err) {
                return;
            }
        });
    },

    // ///////////////////////////////////////////////////

    sendUserStatusChanged: function (reason) {
        this.send("onUserStatusChanged", {
            status: this.user.status,
            reason: reason
        });
    },

    /**
     * 发送用户对应某个参数的改变
     * @param key 表示用户的某个参数改变
     * @param attr 子属性
     */
    sendUserValueChanged: function (key, attr) {
        // 检查是否安全
        if (key == null) {
            return;
        }

        // 当前获取的值
        var value = this.user[key];
        if (attr) {
            value = value[attr];
        }

        // 进行key-value值发送
        this.send("onUserValueChanged", {
            key: key,
            attr: attr,
            value: value
        });
    },

    /**
     * 同步到到游戏服务器
     * @param data
     * @param callback
     */
    syncGameUser: function (data, callback) {
        var uid = this.uid;
        var roomId = roomManager.getUserRoomId(uid);
        if (!roomId) {
            return;
        }

        pomelo.app.rpc.game.userRemote.sync({ rid: roomId }, {
            'rid': roomId,
            uid: uid,
            user: data
        }, callback);
    },

    buildGameUser: function (gameType, subType, scene) {
        var user = this.user;
        var gameUser = clone(user.info);
        gameUser.coin = user.status.coin;
        gameUser.gmLevel = this.getGmLevel();
        gameUser.ip = user.marks.loginIP;
        gameUser.robot = user.robot;
        gameUser.card = user.status.card;
        gameUser.gameStat = this.getGameStat(gameType, scene) || {};
        gameUser.controlValue = this.user.controlValue || 0;

        if (this.isRobot()) {
            gameUser.ip = user.info.createIP;
        }

        return gameUser;
    },

    checkDailyReward: function () {
        if (this.getDayVar('dailyReward')) {
            return;
        }

        var config = gGlobalManager.getConfig("dailyReward");
        if (!config) {
            return;
        }

        if (config['coin'] && this.getResource('coin') < config['coinLT']) {
            this.addResource('coin', config['coin'], "dailyReward");
            this.addDayVar('dailyReward', 1);
            this.send("onPlayerDailyReward", {
                'coin': config['coin'],
                'status': this.user.status,
            });
        }
    },

    checkEvent: function (event, value, arg1) {
        if (this.isRobot()) {
            return;
        }

        //触发活动
        var activityConfig = gGlobalManager.getConfig("Activity");
        if (this._checkActivity(activityConfig, this.user.activity, event, value, arg1)) {
            this.markDirty("activity");
        }

        //触发每日活动
        var dailyActivityConfig = gGlobalManager.getConfig("DailyActivity");
        if (this._checkActivity(dailyActivityConfig, this.user.dailyActivity, event, value, arg1)) {
            this.markDirty("dailyActivity");
        }
    },

    _checkActivity: function (configs, activity, event, value, arg1) {
        if (!configs) {
            return false;
        }

        var changed = false;
        ExObject.each(configs, function (key, config) {
            if (this._checkActivityItem(key, config, activity, event, value, arg1)) {
                changed = true;
            }
        }.bind(this));

        return changed;
    },

    _checkActivityItem: function (key, config, activity, event, value, arg1) {
        if (config.event != event) {
            return false;
        }

        if (config.hasOwnProperty("arg1") && config.arg1 != arg1) {
            return false;
        }

        var activityItem = activity[key];
        if (!activityItem) {
            activityItem = {
                value: 0,
                level: 0,
            }
            activity[key] = activityItem;
            activityItem.value += value;
        }

        return true;
    },

    getGameStat: function (gameType, scene) {
        this.checkDayVars();

        var user = this.user;
        if (!user.gameStat) {
            return;
        }

        var stat = user.gameStat[gameType];
        if (!stat) {
            return;
        }

        return stat[scene];
    },

    addGameStat: function (gameType, scene, key, value) {
        if (this.isRobot()) {
            return;
        }

        var user = this.user;
        if (!user.gameStat) {
            user.gameStat = {};
        }

        var stat = user.gameStat[gameType];
        if (!stat) {
            stat = {};
            user.gameStat[gameType] = stat;
        }

        var sceneStat = stat[scene];
        if (!sceneStat) {
            sceneStat = {};
            stat[scene || 0] = sceneStat;
        }

        ExObject.addNumber(sceneStat, key, value);
        this.markDirty("gameStat");
        return sceneStat[key];
    },

    /**
     * 添加房卡中玩家局数添加
     * @param score
     * @param round  // 表示玩家房卡场中玩的局数
     */
    addCardRoomStat: function (score, round) {
        if (this.isRobot()) {
            return;
        }

        var user = this.user;
        if (!user.playStat) {
            user.playStat = {
                winScore: 0,    // 总赢分
                loseScore: 0,   // 总输分
                play: 0,        // 总次数
                playRound: 0,   // 总局数
            };
        }

        var stat = user.playStat;
        stat.play++;

        if (!isNaN(round)) {
            ExObject.addNumber(stat, "playRound", round);
        }

        if (score > 0) {
            stat.winScore += score;
        } else {
            stat.loseScore -= score;
        }

        this.markDirty("playStat");
        this.sendUserValueChanged("playStat");

        this.addWeekVar("playRound", round);
    },


    addactivitySign: function (monthCount, seriesDays, lastTime) {
        var user = this.user;
        if (!user.activitySign) {
            user.activitySign = {
                monthCount: 0,
                seriesDays: 0,
                lastTime: 0,
                signs: [],
            };
        }
        if (monthCount) {
            user.activitySign.monthCount = monthCount;
        } else {
            user.activitySign.monthCount = 0;
        }
        if (seriesDays) {
            user.activitySign.seriesDays = seriesDays;
        } else {
            user.activitySign.seriesDays = 0;

        }
        if (lastTime) {
            user.activitySign.lastTime = lastTime;
        } else {
            user.activitySign.lastTime = 0;

        }
        user.activitySign.signs = [];
        this.markDirty("activitySign");
        return user.activitySign;
    },

    getactivitySign: function () {
        return this.user.activitySign;
    },

    getActivity: function (key) {
        return this.user.activity[key];
    },

    //-------------------------------------------------------------------------
    // 任务

    getTask: function(taskId) {
        return this.user.tasks[taskId] || {};
    },

    updateTask: function(taskId, task) {
        this.user.tasks[taskId] = task;
        this.markDirty("tasks");

        this.send("onTaskUpdate", {
            taskId: taskId,
            task: task
        });
    },

    //-------------------------------------------------------------------------
    // 绑定手机号

    setTelephone: function(telephone) {
        this.user.telephone.number = telephone;
        this.markDirty("telephone");
        this.send("onTelephoneChange", this.user.telephone);
    },

    setTelephoneCode: function(code) {
        this.user.telephone.code = code;
        this.markDirty("telephone");
    },

    getTelephone: function() {
        return this.user.telephone;
    },

    //-------------------------------------------------------------------------
    // 邮件

    getMails: function() {
        var userMails = this.user.mails;
        var mailList = [];
        for (var key in userMails.mailList) {
            mailList.push(userMails.mailList[key]);
        }
        return mailList;
    },

    addMail: function(content) {
        var userMails = this.user.mails;
        var mail = {
            id: ++userMails.maxMailID,      // 邮件编号
            time: Date.getStamp(),          // 创建时间
            content: content,               // 邮件内容
            status: 0                       // 邮件状态
        };
        userMails.mailList[mail.id] = mail;
        this.markDirty("mails");
        this.send("onNewMail", mail);
    },

    updateMail: function(mailId) {
        var userMails = this.user.mails;

        var mail = userMails.mailList[mailId];
        if (mail) {
            mail.status = 1;
        }
        this.markDirty("mails");
    }
};

exports.Player = Player;